from flask import Blueprint

monitor_info_bp = Blueprint('monitor_info', __name__)
from Test import db
import datetime
import hashlib
from flask import Flask, request, jsonify, abort, g
import json
from utils.tokenUtil import *
import logging


##TODO 调整字段属性
class MonitorInfo(db.Model):
    __tablename__ = 'monitor_info'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, nullable=True)
    index_first = db.Column(db.String(255), nullable=True)
    index_second = db.Column(db.String(255), nullable=True)
    condition_type = db.Column(db.String(255), nullable=True)
    condition_detail = db.Column(db.String(2000), nullable=True)
    date_start = db.Column(db.Date, nullable=True)
    date_end = db.Column(db.Date, nullable=True)
    frequency_datesize = db.Column(db.String(255), nullable=True)
    frequency_number = db.Column(db.Integer, nullable=True)
    push_channel = db.Column(db.String(255), nullable=True)
    deleted = db.Column(db.Integer, nullable=True)
    status = db.Column(db.Integer, nullable=True)
    create_time = db.Column(db.DateTime, nullable=True)
    update_time = db.Column(db.DateTime, nullable=True)

def to_dict_value(self):
    return {
        'id': self.id,
        'index_first': self.index_first,
        'index_second': self.index_second,
        'frequency_datesize': self.frequency_datesize,
        'status': self.status,
    }

##订阅列表
@monitor_info_bp.route('/monitor_info/list', methods=['GET'])
@token_required
def list_monitor_info():
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        query = MonitorInfo.query.filter_by(user_id=g.user_id).filter_by(deleted=0)

        query = query.order_by(MonitorInfo.create_time.desc())
        pagination = query.paginate(page=page, per_page=per_page, error_out=False)
        data = [to_dict_value(msg) for msg in pagination.items]

        return jsonify({
            'data': {
                'data': data,
                'total': pagination.total,
                'pages': pagination.pages,
                'current_page': pagination.page,
                'per_page': pagination.per_page,
            },
            'message': 'success',
            'status': 200
        })
    except Exception as e:
        logging.error('获取用户消息失败,错误原因为：%s', str(e))
        return jsonify({
            'data': '',
            'message': 'exception',
            'status': 500
        })

##创建订阅接口
@monitor_info_bp.route('/monitor_info/add', methods=['POST'])
@token_required
def create_monitor_info():
    data = request.get_json()

    new_monitor_info = MonitorInfo(
        user_id=g.user_id,
        index_first=data['index_first'],
        index_second=data['index_second'],
        condition_type=data['condition_type'],
        condition_detail=json.dumps(data['condition_detail']),
        date_start=data['date_start'],
        date_end=data['date_end'],
        frequency_datesize=data['frequency_datesize'],
        frequency_number=data['frequency_number'],
        push_channel=data['push_channel'],
        create_time=datetime.datetime.utcnow(),
        update_time=datetime.datetime.utcnow()
    )
    db.session.add(new_monitor_info)
    db.session.commit()
    return jsonify({
        # 'data': new_user.user_name,
        'message': 'Create successful',
        'status': 200
    })

##修改订阅接口
@monitor_info_bp.route('/monitor_info/edit', methods=['POST'])
@token_required
def edit_monitor_info():
    try:
        data = request.get_json()
        monitorInfo = MonitorInfo.query.filter_by(user_id=g.user_id).filter_by(id=data['id']).first()
        if monitorInfo:
            monitorInfo.index_first = data['index_first']
            monitorInfo.index_second = data['index_second']
            monitorInfo.condition_type = data['condition_type']
            monitorInfo.condition_detail = json.dumps(data['condition_detail'])
            monitorInfo.date_start = data['date_start']
            monitorInfo.date_end = data['date_end']
            monitorInfo.index_first = data['frequency_datesize']
            monitorInfo.index_first = data['frequency_number']
            monitorInfo.index_first = data['push_channel']
            monitorInfo.update_time = datetime.datetime.utcnow()
            db.session.commit()
            return jsonify({
                'data': {},
                'message': 'success',
                'status': 200
            })
        return jsonify({
            'data': '',
            'message': 'data not exist',
            'status': 500
        })
    except Exception as e:
        logging.error('获取用户消息失败,错误原因为：%s', str(e))
        return jsonify({
            'data': '',
            'message': 'exception',
            'status': 500
        })
##修改订阅状态
@monitor_info_bp.route('/monitor_info/status', methods=['POST'])
@token_required
def status_monitor_info():
    try:
        data = request.get_json()
        monitorInfo = MonitorInfo.query.filter_by(user_id=g.user_id).filter_by(id=data['id']).first()
        if monitorInfo:
            monitorInfo.status = data['status']
            monitorInfo.update_time = datetime.datetime.utcnow()
            db.session.commit()
            return jsonify({
                'data': {},
                'message': 'success',
                'status': 200
            })
        return jsonify({
            'data': '',
            'message': 'data not exist',
            'status': 500
        })
    except Exception as e:
        logging.error('修改订阅状态失败,错误原因为：%s', str(e))
        return jsonify({
            'data': '',
            'message': 'exception',
            'status': 500
        })

##删除订阅
@monitor_info_bp.route('/monitor_info/delete', methods=['POST'])
@token_required
def delete_monitor_info():
    try:
        data = request.get_json()
        monitorInfo = MonitorInfo.query.filter_by(user_id=g.user_id).filter_by(id=data['id']).first()
        if monitorInfo:
            monitorInfo.deleted = 1
            monitorInfo.update_time = datetime.datetime.utcnow()
            db.session.commit()
            return jsonify({
                'data': {},
                'message': 'success',
                'status': 200
            })
        return jsonify({
            'data': '',
            'message': 'data not exist',
            'status': 500
        })
    except Exception as e:
        logging.error('删除订阅失败,错误原因为：%s', str(e))
        return jsonify({
            'data': '',
            'message': 'exception',
            'status': 500
        })

##订阅详情
@monitor_info_bp.route('/monitor_info/detail', methods=['POST'])
@token_required
def detail_monitor_info():
    try:
        request_data = request.get_json()
        id = request_data.get('id')
        monitor_info = MonitorInfo.query.filter_by(user_id=g.user_id).filter_by(id=id).first()
        if monitor_info is None:
            return jsonify({
                'data': {},
                'message': 'data not exist',
                'status': 500
            })
        condition_detail = json.loads(monitor_info.condition_detail)
        data = {
            "id": monitor_info.id,
            "index_first": monitor_info.index_first,
            "index_second": monitor_info.index_second,
            "condition_type": monitor_info.condition_type,
            "condition_detail": condition_detail,
            "date_start": monitor_info.date_start,
            "date_end": monitor_info.date_end,
            "frequency_datesize": monitor_info.frequency_datesize,
            "frequency_number": monitor_info.frequency_number,
            "push_channel": monitor_info.push_channel
        }

        return jsonify({
            'data': data,
            'message': 'get message detail success',
            'status': 200
        })
    except Exception as e:
        logging.error('获取用户消息失败,错误原因为：%s', str(e))
        return jsonify({
            'data': '',
            'message': 'exception',
            'status': 500
        })



